package com.zjh.common.SSE.controller;

import com.zjh.common.SSE.service.SSEService;
import com.zjh.common.utils.IpUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;


@RestController
@RequestMapping("/sse")
@Slf4j
public class SseController {

    @Resource
    private SSEService sseService;

    @GetMapping(path = "/connect", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public SseEmitter connect(
            HttpServletRequest request,
            @RequestParam String pageType,
            @RequestParam String type,
            @RequestParam String username) {

        String clientIp = IpUtils.getIpAddr(request);

        String clientId = sseService.getClientId(pageType, type, username, clientIp);
        log.info("------------------------");
        log.info(clientId);

        SseEmitter emitter = new SseEmitter(Long.MAX_VALUE);

        sseService.registerSSEClient(clientId, emitter);

        return emitter;

    }
}